package jschool.util;

import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.io.File;

public class VisualizadorImagen extends JComponent implements
		PropertyChangeListener {

	private static final long serialVersionUID = 1L;
	ImageIcon iconoMostrar = null;
	File f = null;

	public VisualizadorImagen(JFileChooser fc) {
		setPreferredSize(new Dimension(117, 100));
		fc.addPropertyChangeListener(this);
	}

	public void cargarImagen() {
		if (f == null)
			return;

		ImageIcon icono = new ImageIcon(f.getPath());
		if (icono.getIconWidth() > this.getWidth() - 10) {
			iconoMostrar = new ImageIcon(icono.getImage().getScaledInstance(
					this.getWidth() - 10, -1, Image.SCALE_DEFAULT));
		} else {
			iconoMostrar = icono;
		}
	}

	public void propertyChange(PropertyChangeEvent e) {
		String prop = e.getPropertyName();
		if (prop.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
			f = (File) e.getNewValue();
			if (isShowing()) {
				cargarImagen();
				repaint();
			}
		}
	}

	public void paint(Graphics g) {
		if (iconoMostrar == null) {
			cargarImagen();
		}
		if (iconoMostrar != null) {
			int x = getWidth() / 2 - iconoMostrar.getIconWidth() / 2;
			int y = getHeight() / 2 - iconoMostrar.getIconHeight() / 2;

			if (y < 0) {
				y = 0;
			}

			if (x < 5) {
				x = 5;
			}
			iconoMostrar.paintIcon(this, g, x, y);
		}
	}
}
